package com.mrd.gtimp.login.action;

import com.mrd.constant.MsgConstants;
import com.mrd.constant.SystemConstants;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.base.entity.Module;
import com.mrd.gtimp.base.entity.Permissions;
import com.mrd.gtimp.base.entity.Role;
import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimp.base.service.UserBiz;
import com.mrd.util.endecrypt.MD5Util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

/**
 * <p> application name: sample <p> copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author winaya
 */
@Controller
@RequestMapping("/")
public class LoginAction {
    private static final long serialVersionUID = 1L;

    private Map<String, Object> sessionMap;
    ;//= ActionContext.getContext().getSession();

//    /**
//     * 获取request
//     */
//    protected HttpServletRequest request = ServletActionContext.getRequest();
//    /**
//     * 获取response
//     */
//    protected HttpServletResponse response = ServletActionContext.getResponse();

    @Resource
    private UserBiz userBiz;

    private String userName;

    private String pwd;

    private String msg;

    private static final String NO_LOGIN_STRING = "nologin";
    private static final String LOGIN_DELETE = "login_delete";
    private static final String LOGIN_NO_ACTIVE = "login_no_active";
    private static final String LOGIN_ERROR = "login_error";

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "/gtimp/login";
    }

    @RequestMapping("/login-execute")
    public String execute() {
        try {
            User user = (User) sessionMap.get(SystemConstants.CURRENT_USER);
            if (user == null) {
                return "/gtimp/login";
            } else {
                //// TODO: 2016/8/17 SUCCESS
                return null;
            }
        } catch (Exception e) {

        }
        return null;
    }

    public String out() {
        sessionMap.remove(SystemConstants.CURRENT_USER);
        return NO_LOGIN_STRING;
    }

    /**
     * 报关一线通网址登陆
     */
    @RequestMapping("/login-ajax_login")
    public String ajax_login() {
        HttpUtils.getRequest().setAttribute("callback", HttpUtils.getParam("callback"));
        if ("success".equals(login())) {
            msg = MsgConstants.OPERATION_SUCCESS;
        } else if (LOGIN_ERROR.equals(login())) {
            msg = MsgConstants.LOGIN_ERROR;
        } else if (LOGIN_DELETE.equals(login())) {
            msg = MsgConstants.LOGIN_DELETE;
        } else if (LOGIN_NO_ACTIVE.equals(login())) {
            msg = MsgConstants.LOGIN_NO_ACTIVE;
        } else {
            msg = MsgConstants.OPERATION_FAIL;
        }
        return "/msgText";
    }

    /**
     * 登錄
     */
    @RequestMapping("/login-login")
    public String login1() {
        try {
            User user = null;
            if (StringUtils.isNotBlank(userName) && StringUtils.isNotBlank(pwd)) {
                userName = userName.trim();
                pwd = pwd.trim();
                Filter filter = new Filter();
                filter.addRule(new SearchRule("account", SearchRuleOption.eq, userName));
                filter.addRule(new SearchRule("pwd", SearchRuleOption.eq, MD5Util.string2MD5(pwd)));
                List<User> users = userBiz.findEntityByFilter(0, 0, filter, null);


                if (users == null || users.size() == 0) {
                    msg = "用户名或密码错误!";
                    return LOGIN_ERROR;
                } else {
                    user = users.get(0);
                    if ("1".equals(user.getState())) {
                        msg = "很遗憾，该用户已被删除，请联系公司管理员!";
                        return LOGIN_DELETE;
                    } else if ("1".equals(user.getIsabled())) {
                        msg = "很遗憾，该用户已被禁用或者未激活，请联系公司管理员!";
                        return LOGIN_NO_ACTIVE;
                    } else {
                        // 加载权限和模块
                        Set<Module> userModules = new HashSet<Module>();
                        Set<Module> userManageModules = new HashSet<Module>();
                        Set<Permissions> userPermissions = new HashSet<Permissions>();
                        Set<Permissions> userManagePermissions = new HashSet<Permissions>();
                        List<Role> roles = user.getRoles();
                        if (roles != null && roles.size() != 0) {
                            for (Role role : roles) {
                                List<Module> modules = role.getModules();
                                List<Module> manageModules = role.getManageModules();
                                List<Permissions> permissions = role.getPermissions();
                                List<Permissions> managePermissions = role.getManagePermissions();
                                userModules.addAll(modules);
                                userManageModules.addAll(manageModules);
                                userPermissions.addAll(permissions);
                                userManagePermissions.addAll(managePermissions);
                            }
                            user.setModules(new ArrayList<Module>(userModules));
                            user.setManageModules(new ArrayList<Module>(userManageModules));
                            user.setPermissions(new ArrayList<Permissions>(userPermissions));
                            user.setManagePermissions(new ArrayList<Permissions>(userManagePermissions));
                        }
                        user.getDepts();
                        user.getCompany();
                        sessionMap.put(SystemConstants.CURRENT_USER, user);
                        return "success";
                    }
                }
            } else {
                msg = "用户名或者密码为空!";
                return NO_LOGIN_STRING;
            }
        } catch (Exception e) {
            msg = "登录失败，系统错误!";
            e.printStackTrace();
        }
        return NO_LOGIN_STRING;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

}
